package com.yxgc.chat.wildfire.nativelib;

import android.content.Context;
import android.util.Log;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.yxgc.chat.wildfire.nativelib.util.EventCmd;

import java.util.Collections;
import java.util.List;

import cn.wildfirechat.client.NotInitializedExecption;
import cn.wildfirechat.message.Message;
import cn.wildfirechat.model.Conversation;
import cn.wildfirechat.model.ConversationInfo;
import cn.wildfirechat.remote.ChatManager;
import cn.wildfirechat.remote.OnClearMessageListener;
import cn.wildfirechat.remote.OnConnectionStatusChangeListener;
import cn.wildfirechat.remote.OnConversationInfoUpdateListener;
import cn.wildfirechat.remote.OnDeleteMessageListener;
import cn.wildfirechat.remote.OnRecallMessageListener;
import cn.wildfirechat.remote.OnReceiveMessageListener;
import cn.wildfirechat.remote.OnRemoveConversationListener;
import cn.wildfirechat.remote.OnSendMessageListener;

public class ChatHelper implements OnReceiveMessageListener,
        OnSendMessageListener,
        OnRecallMessageListener,
        OnDeleteMessageListener,
        OnConversationInfoUpdateListener,
        OnRemoveConversationListener,
        OnConnectionStatusChangeListener,
        OnClearMessageListener {

    private ReactApplicationContext reactContext;

    private static ChatHelper chatHelper;
    public ChatManager chatManager;

    private ConversionListModel conversionListModel;
    private ContractModel contractModel;
    private ConversionModel conversionModel;

    private void sendEvent(ReactContext reactContext,
                           String eventName,
                           WritableMap params) {
        reactContext
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, params);
    }

    private ChatHelper(ReactApplicationContext reactContext) {

        this.reactContext = reactContext;
    }

    public static ChatHelper getInstance(ReactApplicationContext reactContext) {
        if (chatHelper == null) {
            chatHelper = new ChatHelper(reactContext);
        }
        return chatHelper;
    }
    public static void  test(){

    }

    /**
     * 初始化
     */
    public void chatInit(Context context, String hostUrl) {

        chatManager = new ChatManager(hostUrl);
        if (chatManager != null) {

            chatManager.init(context, hostUrl);
            conversionListModel = new ConversionListModel();
            contractModel = new ContractModel();
            conversionModel = new ConversionModel();
            try {
                chatManager.startLog();
            } catch (NotInitializedExecption notInitializedExecption) {
                notInitializedExecption.printStackTrace();
            }
            ChatManager.Instance().addOnReceiveMessageListener(this);
            ChatManager.Instance().addSendMessageListener(this);
            ChatManager.Instance().addConversationInfoUpdateListener(this);
            ChatManager.Instance().addRecallMessageListener(this);
            ChatManager.Instance().addConnectionChangeListener(this);
            ChatManager.Instance().addDeleteMessageListener(this);
            ChatManager.Instance().addClearMessageListener(this);
            ChatManager.Instance().addRemoveConversationListener(this);
        } else {
        }

    }

    /**
     * 连接
     */
    public boolean chatConnect(String id, String token) {
        boolean isConnect = chatManager.connect(id, token);
        return isConnect;
    }


    /**
     * 聊天列表
     */
    public void getConversionList(Callback successCallback, Callback errorCallback) {
        Log.e("yxgc", "聊天列表 getConversionList");
        conversionListModel.loadConversationList(successCallback, errorCallback);
    }

    public void reloadConversationUnreadStatus(Callback successCallback, Callback errorCallback) {
        conversionListModel.reloadConversationUnreadStatus(successCallback, errorCallback);
    }


    public void getFriendList(Callback successCallback) {
        contractModel.getFriendList(successCallback);
    }

    /**
     * 创建群聊
     */
    public void createGroup(String groupName, List<String> selectedIds, Callback callback) {
        contractModel.createGroup(groupName, selectedIds, callback);
    }

    /**
     * 添加好友
     */
    public void addFriend(String targetUid, String reason, Callback callback) {
        contractModel.addFriend(targetUid, reason, callback);
    }

    public void getFriendRequest(Callback callback) {
        contractModel.getFriendRequest(callback);
    }

    /**
     * 添加好友
     */
    public void acceptFriendRequest(String targetUid, Callback callback) {
        contractModel.handleFriendRequest(targetUid, callback);
    }

    public void getConversionTitle(String target, String conversionType, Callback callback) {
        conversionModel.getConversionTitle(target, conversionType, callback);
    }

    /**
     * 加载会话消息
     */
    public void getMessage(String conversion, Callback callback, Callback errBack) {
        conversionModel.loadMessage(conversion, callback, errBack);
    }

    public void sendTxt(String conversation, String content, Callback callback) {
        conversionModel.sendTxtMsg(conversation, content, callback);
    }

    public void sendVideo(String conversation, String filePath, Callback c) {
        conversionModel.sendVideoMsg(conversation, filePath, c);
    }

    public void sendAudio(String conversation, String audioFilePath, int duration, Callback callback) {
        conversionModel.sendAudioFile(conversation, audioFilePath, duration, callback);
    }

    public void sendImg(String conversation, String imageFileThumbPath, String imageFileSourcePath, Callback callback) {
        conversionModel.sendImgMsg(conversation, imageFileThumbPath, imageFileSourcePath, callback);
    }

    /**
     * 修改群名称
     */
    public void modifyGroupName(String groupId, int modifyType, String newValue, Callback callback) {
        contractModel.modifyGroupName(groupId, modifyType, newValue, null, Collections.singletonList(0));
    }

    /**
     * 退出群聊
     */
    public void quiteGroup(String groupId, Callback callback) {
        contractModel.quiteGroup(groupId, callback);
    }

    /**
     * 删除好友
     */
    public void deleteFriend(String userId, Callback callback) {
        contractModel.deleteFriend(userId, callback);
    }

    /**
     * 设置用户昵称
     */
    public void setFriendAlias(String userId, String alias, Callback callback) {
        contractModel.setFriendAlias(userId, alias, callback);
    }

    /**
     * 获取用户昵称
     */
    public void getFriendAlias(String userId, Callback callback) {
        contractModel.getFriendAlias(userId, callback);
    }

    @Override
    public void onClearMessage(Conversation conversation) {

    }
    /**
     *  eventName CONVERSION_CHANGE
     *  无参数
     * */
    @Override
    public void onConnectionStatusChange(int status) {
        WritableMap params = Arguments.createMap();
        params.putInt("onConnectionStatusChange", status);
        sendEvent(reactContext, EventCmd.CONNECT_STATE, params);
    }

    @Override
    public void onConversationDraftUpdate(ConversationInfo conversationInfo, String draft) {

    }

    @Override
    public void onConversationTopUpdate(ConversationInfo conversationInfo, boolean top) {
        sendEvent(reactContext, EventCmd.CONVERSION_CHANGE, null);
    }

    @Override
    public void onConversationSilentUpdate(ConversationInfo conversationInfo, boolean silent) {
        sendEvent(reactContext, EventCmd.CONVERSION_CHANGE, null);
    }

    @Override
    public void onConversationUnreadStatusClear(ConversationInfo conversationInfo) {
        sendEvent(reactContext, EventCmd.CONVERSION_CHANGE, null);
    }

    @Override
    public void onDeleteMessage(Message message) {
        sendEvent(reactContext, EventCmd.RECEIVE_MSG, null);
    }

    @Override
    public void onRecallMessage(Message message) {

    }

    @Override
    public void onReceiveMessage(List<Message> messages, boolean hasMore) {
        sendEvent(reactContext, EventCmd.RECEIVE_MSG, null);
    }

    @Override
    public void onConversationRemove(Conversation conversation) {
        sendEvent(reactContext, EventCmd.CONVERSION_CHANGE, null);
    }

    @Override
    public void onSendSuccess(Message message) {

    }

    @Override
    public void onSendFail(Message message, int errorCode) {

    }

    @Override
    public void onSendPrepare(Message message, long savedTime) {

    }
}
